from flask import Flask
from werkzeug.utils import secure_filename
import os

class Upload:
    def __init__(self):
        self.photos_path = 'static/upload/photos'
        self.allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}

    def init_upload(self, app: Flask):
        # 确保上传目录存在
        upload_path = os.path.join(app.root_path, self.photos_path)
        os.makedirs(upload_path, exist_ok=True)
        
        # 设置上传文件大小限制（默认16MB）
        app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
        
        # 设置上传路径
        app.config['UPLOAD_FOLDER'] = self.photos_path

    def allowed_file(self, filename):
        return '.' in filename and \
            filename.rsplit('.', 1)[1].lower() in self.allowed_extensions

    def save_file(self, file, app: Flask):
        if file and self.allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.root_path, self.photos_path, filename))
            return os.path.join(self.photos_path, filename)
        return None

photos = Upload()
init_upload = photos.init_upload
